import re
from django import http
from django.contrib.auth import login
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View

from apps.users.models import User


class RegisterView(View):
    """用户注册"""
# 注册界面显示
    def get(self, request):
        """
        提供注册界面
        :param request: 请求对象
        :return: 注册界面
        """
        return render(request, 'register.html')

    # 注册功能提交
    def post(self,request):# 请求方式post
        # 1.用户名
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        #短信验证码
        # sms_code = request.POST.get('sms_code')

        # 5.是否同意协议 allow
        allow = request.POST.get('allow')
        # 判空all()
        if not all([username,password,password2,mobile]):
            return http.HttpResponseForbidden('参数不齐')
        # 校验参数正则校验re.match
        # 校验参数用户名
        if not re.match('^[a-zA-Z0-9_-]{5,20}$',username):
            return http.HttpResponseForbidden('请输入5-20个字符')
        # 校验参数密码正则
        if not re.match('^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20密码')
        # 校验参数手机号
        if not re.match('^1[345789]\d{9}$', mobile):
            return http.HttpResponseForbidden('您输入的手机号格式不正确')
        # 校验参数密码是否一致
        if password != password2:
            return http.HttpResponseForbidden('两次密码不一致')
        # 勾选同意
        if not allow == 'on':
            return http.HttpResponseForbidden('请勾选同意协议')
        # 6.注册用户

        user = User.objects.create_user(username=username,password=password,mobile=mobile)
        # 7.保持登陆状态
        login(request,user)
        # 8.重定向首页
        return redirect('/')